package fr.utbm.aiechat.packets;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;

import fr.utbm.aiechat.Network;
import fr.utbm.aiechat.structures.Channel;

public class ChanListResponsePacket
{
	private DatagramPacket packet;
	
	public ChanListResponsePacket(InetAddress Address, int Port) throws SocketException
	{
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		DataOutputStream data = new DataOutputStream(stream);
		
		try
		{
			// The PacketType
			data.writeInt(Packets.CHANLIST_RESPONSE);
		
			int chan_count = Network.getInstance().getConversationsCount();
			
			
			ArrayList<Channel> PublicChans = new ArrayList<Channel>();
			
			// Let's count how many public Channel do I own.
			for(int i = 0; i < chan_count; i++)
			{
				Channel chan = Network.getInstance().getConversation(i).getChannel();
				
				if(!chan.isPrivate())
					PublicChans.add(chan);
			}
			
			// Write the number of channels
			data.writeInt(PublicChans.size());
			
			// maybe replace with a iterator
			for(int i = 0; i < PublicChans.size(); i++)
			{
				Channel chan = PublicChans.get(i);
				
				// This is a public channel
				// Write its Unique ID
				data.writeInt(chan.getUniqueID());
				
				// Write the Channel Port
				data.writeInt(chan.getPort());
				
				// and its name
				data.writeUTF(chan.getName());
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		packet = new DatagramPacket(stream.toByteArray(), stream.size(), Address, Port);
	}
	
	public DatagramPacket getPacket()
	{
		return packet;
	}
}